<template>
  <div class="houseManage">
    <el-tabs type="card" @edit="handleTabsEdit" v-model="tableTabsValue">
      <el-tab-pane label="房源列表" name="houseList">
        <el-form :inline="true" :model="findHouse" class="findHouse" size="mini">
          <el-form-item label="出租类型:" label-width="80px" class="houseType">
            <el-select v-model="findHouse.rentType" placeholder="请选择出租类型" clearable style="width: 150px">
              <el-option v-for="item in rentType" :label="item.rentTypeStr" :value="item.rentType" :key="item.rentType"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="户型:" label-width="80px">
            <el-select v-model="findHouse.houseType" placeholder="请选择户型" clearable style="width: 150px">
              <el-option v-for="item in houseType" :label="item.label" :value="item.value" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签" label-width="80px">
            <el-select v-model="findHouse.tagList" clearable multiple allow-create>
              <el-option v-for="item in allTagList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="大小:" label-width="80px">
            <el-input v-model="findHouse.minArea" class="houseArea"></el-input>
          </el-form-item>
          <el-form-item label="至">
            <el-input v-model="findHouse.maxArea" class="houseArea"></el-input>㎡
          </el-form-item>
<!--          <br v-show="otherCondition">-->
          <el-form-item label="房租:" label-width="80px" v-show="otherCondition">
            <el-input v-model="findHouse.minRentMoney" class="rentMoney" clearable></el-input>
          </el-form-item>
          <el-form-item label="至" v-show="otherCondition">
            <el-input v-model="findHouse.maxRentMoney" class="rentMoney" clearable></el-input>元/月
          </el-form-item>

          <el-form-item label="地址：" label-width="120px" v-show="otherCondition">
            <el-select v-model="findHouse.province" class="address" clearable style="width: 150px">
              <el-option v-for="item in provinceList" :label="item.name" :value="item.name" :key="item.id"></el-option>
            </el-select>省
            <el-select v-model="findHouse.city" class="address" clearable style="width: 150px">
              <el-option v-for="item in cityList" :label="item.name" :value="item.name" :key="item.id"></el-option>
            </el-select>市
            <el-select v-model="findHouse.county" class="address" clearable style="width: 150px">
              <el-option v-for="item in countyList" :label="item.name" :value="item.name" :key="item.id"></el-option>
            </el-select>区(县)
          </el-form-item>

          <el-form-item label="检索输入" label-width="100px" v-show="otherCondition">
            <el-input v-model="findHouse.condition" clearable placeholder="请输入房东的id或名字"></el-input>
          </el-form-item>

          <span class="otherCondition" @click="changeOtherCondition">
            <i v-if="!otherCondition" class="el-icon-caret-bottom"></i>
            <i v-if="otherCondition" class="el-icon-caret-top"></i>更多搜索
          </span>

          <el-button type="primary" size="mini" @click="findHouseByCondition">查询</el-button>
          <el-button type="primary" size="mini" @click="addHouseResource">增加房源</el-button>
        </el-form>
        <div style="margin-left:1%;margin-right:1%" class="houseList">
          <el-row>
            <el-col :span="12" v-for="item in houseList" :key = "item.id">
              <div style="margin: 10px">
                <el-card :body-style="{padding:'0px'}" shadow="hover">
                  <img :src="item.picList.length==0?'':baseUrl+item.picList[0].url" class="hoseImage">
                  <div class="simple">
                    <span>{{item.rentType==0?"整租":"合租"}} | {{item.houseTypeStr}} | {{item.area}}㎡ | {{item.buildTime}} 年建</span>
                  </div>
                  <div class="price">
                    <span>{{item.money}}</span>元/月
                  </div>
                  <div class="tag">
                    <el-row style="height: 50px ">
                      <el-tag  v-for="tagItem in item.tagList" :key="tagItem.id" size="mini">{{tagItem.name}}</el-tag>
                    </el-row>
                  </div>
                  <div class="describe">
                    所在地址：<span>{{item.province}}{{item.city}}{{item.county}}{{item.address}}</span>
                  </div>
                  <div class="funBtn">
                    <div class="houseState">
                      <div class="stateTitle" style="line-height: 42px">状态：</div>
                      <el-tag v-if="item.state==0">审核中</el-tag>
                      <el-tag type="success" v-if="item.state==1">正在出租</el-tag>
                      <el-tag type="info" v-if="item.state==2">已出租</el-tag>
                      <el-tag type="danger" v-if="item.state==3">审核失败</el-tag>
                    </div>
                    <div class="options">
                      <el-button type="primary" size="small" @click="changeHouseInfo(item) " class="changeHouseInfo" v-if="user.role==2">审核</el-button>
                      <el-button type="primary" size="small" @click="changeHouseInfo(item) " class="changeHouseInfo" v-if="user.role!=2">查看</el-button>
                      <el-button type="primary" size="small" @click="deleteHouse(item.id)" class="changeHouseInfo" v-if="user.role!=2">删除</el-button>
                    </div>
                  </div>
                </el-card>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-pagination
          class="housePage"
          @size-change="sizeChange"
          @current-change="currentChange"
          @prev-click="prevClick"
          @next-click="nextClick"
          background
          layout="total,sizes,prev, pager, next"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          :total="housePage.count">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane v-for="item in tabList" :label="item.title" :name="item.name" :key="item.name" closable="closable">
        <div class="changeHouse" v-show="paneShow.updateHouse">
          <el-carousel :interval="4000" type="card" height="400px">
            <el-carousel-item v-for="item in changingHouse.picList" :key="item.id">
              <img :src="baseUrl+item.url"  width="400" height="320">
            </el-carousel-item>
          </el-carousel>
          <div class="houseInfo">
            <div class="houseInfoTitle"><span>房屋信息</span></div>
            <div><span class="houseMoney">{{changingHouse.money}}</span>元/月</div>
            <el-divider></el-divider>
            <div class="houseInfoContent">
              <el-row :gutter="30">
                <el-col :span="6">所在地区：{{changingHouse.province+'省'+changingHouse.city+'市'+changingHouse.county+'县'}}</el-col>
                <el-col :span="6">地址：{{changingHouse.address}}</el-col>
                <el-col :span="6">面积：{{changingHouse.area}}平方米</el-col>
                <el-col :span="6">户型：{{changingHouse.houseTypeStr}}</el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="6">层数：{{changingHouse.floor}}</el-col>
                <el-col :span="6">修建时间：{{changingHouse.buildTime}}</el-col>
                <el-col :span="6"></el-col>
                <el-col :span="6"></el-col>
              </el-row>
            </div>
            <el-divider></el-divider>
            <div class="houseInfoDescribe">
              <div class="describeTitle">
                <span>房源描述</span>
              </div>
              <div class="describeContent">
                <span>{{changingHouse.describe}}</span>
              </div>
            </div>
            <div class="checkBtn">
              <el-button type="primary" size="small" @click="verifySuccess" v-if="user.role!=1">审核通过</el-button>
              <el-button type="primary" size="small" @click="verifyFail" v-if="user.role!=1">审核不通过</el-button>
              <el-button type="primary" size="small" @click="cancel">取消</el-button>
            </div>
          </div>
        </div>
        <el-steps :active="addHouseStep" class="addStep" direction="vertical">
          <el-step title="填写基本信息"></el-step>
          <el-step title="添加图片，标签"></el-step>
        </el-steps>
        <div class="addHouse" v-show="paneShow.addHouse">
          <div class="houseBaseInfo" v-show="houseBaseInfoShow">
            <el-form class="addHouseForm" :model="addHouseForm" :rules="addHouseRules" ref="addHouseForm" size="small">
              <el-form-item label="地址：">
                <el-cascader v-model="addHouseForm.add"
                             :options="addressOptions"
                             filterable
                             :props="{ expandTrigger: 'hover' }" style="float: right">

                </el-cascader>
              </el-form-item>
              <el-form-item label="具体地址：">
                <el-input v-model="addHouseForm.address" placeholder="请输入房源具体地址" class="addHouseInput"></el-input>
              </el-form-item>
              <el-form-item label="租金：(元/月)">
                <el-input v-model="addHouseForm.money" placeholder="请输入房源价格" class="addHouseInput"></el-input>
              </el-form-item>
              <el-form-item label="面积：">
                <el-input v-model="addHouseForm.area" placeholder="请输入房源面积" class="addHouseInput"></el-input>
              </el-form-item>
              <el-form-item label="描述（可不填）：">
                <el-input v-model="addHouseForm.describe" placeholder="请输入描述" class="addHouseInput"></el-input>
              </el-form-item>
              <el-form-item label="房源户型：">
<!--                <el-select v-model="addHouseForm.tingType" class="addHouseType">-->
<!--                  <el-option v-for="item in houseTypeOptions" :label="item.value+'厅'" :value="item.value" :key="item.index"></el-option>-->
<!--                </el-select>-->
<!--                <el-select v-model="addHouseForm.shiType" class="addHouseType">-->
<!--                  <el-option v-for="item in houseTypeOptions" :label="item.value+'室'" :value="item.value" :key="item.index"></el-option>-->
<!--                </el-select>-->
                <el-select v-model="addHouseForm.houseType" class="addHouseType">
                  <el-option v-for="item in houseType" :label="item.label" :value="item.value" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="房源所在楼层：">
                <el-input v-model="addHouseForm.floor" placeholder="请输入房源楼层" class="addHouseInput"></el-input>
              </el-form-item>
              <el-form-item label="房源修建时间：">
                <el-input v-model="addHouseForm.buildTime" placeholder="请输入房源修建时间" class="addHouseInput"></el-input>
              </el-form-item>
              <el-form-item label="出租类型：">
                <el-radio-group v-model="addHouseForm.rentType" @change="roommates">
                  <el-radio label="合租" value="1"></el-radio>
                  <el-radio label="整租" value="0"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="合租人数：" v-show="peopleView">
                  <el-input v-model="addHouseForm.peopleNum" placeholder="合租人数" class="addHouseInput"></el-input>
              </el-form-item>
              <el-button type="primary" size="small" @click="nextStep">下一步</el-button>
            </el-form>
          </div>
          <div v-show="!houseBaseInfoShow">
            <el-select v-model="chooseTag">
              <el-option v-for="item in allTagList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
            <el-button type="primary" size="small" @click="addTag" style="margin-left: 10px;">添加</el-button>

            <div>
              <el-tag
                v-show="chooseTagList.length>0"
                v-for="tag in chooseTagList"
                :key="tag.name"
                @close="closeTag(tag)"
                closable>
                {{tag.name}}
              </el-tag>
            </div>
            <div>
              <div class="title" style="font-size: 10px;color: red">定位不准确，请手动选择位置</div>
              <div id="myMap"></div>
            </div>
            <el-upload class="upload-demo"
                       :action="uploadPicUrl"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       :file-list="fileList"
                       :headers="uploadHeaders"
                       auto-upload="auto-upload"
                       list-type="picture-card"
                       :before-upload="beforeUpload"
                       :on-success="housePicUpload">
              <i slot="default" class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="baseUrl+dialogImageUrl">
            </el-dialog>
            <div class="addBtn">
              <el-button type="primary" size="small" @click="prevStep">上一步</el-button>
              <el-button type="primary" size="small" @click="add">添加</el-button>
              <el-button type="primary" size="small" @click="cancel">取消</el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {base} from "../../config";
import {baseMessage} from "../../network/message";


export default {
  name: "HouseManage",
  data(){
    return{
      baseMessage:baseMessage,
      mapInited:false,
      key:base.key,
      getLocationUrl: base.getLocationUrl,
      map:{
        longitude:'',
        latitude:'',
      },
      chooseTag:'',
      addHouseStep:0,
      houseBaseInfoShow:true,
      allTagList:[

      ],
      chooseTagList:[

      ],
      housePageParams:{
        pageNo:1,
        pageSize:10,
        count: 0,
      },
      baseUrl: base.picLocal,
      uploadPicUrl:base.baseUrl+"/houseResource/uploadPic",
      uploadHeaders:{},
      dialogImageUrl:'',
      dialogVisible:false,
      uploadPhotoList:[

      ],
      fileList: [

      ],
      peopleView:true,
      houseTypeOptions:[
        {
          index:1,
          value:"一"
        },
        {
          index: 2,
          value: "二"
        },
        {
          index: 3,
          value: "三"
        },
        {
          index: 4,
          value: "四"
        },
        {
          index: 5,
          value: "五"
        }
      ],
      addressOptions:[
        {
          value:'四川省',
          label:'四川省',
          children:[
            {
              value:'成都市',
              label:'成都市',
              children:[
                {
                  value:'武侯区',
                  label:'武侯区',

                },
                {
                  value: '高新区',
                  label: '高新区',
                },
                {
                  value: '锦江区',
                  label: '锦江区',
                },
                {
                  value: '金牛区',
                  label: '金牛区',
                },
                {
                  value: '成华区',
                  label: '成华区',
                },
                {
                  value: '龙泉驿区',
                  label: '龙泉驿区',
                },
                {
                  value: '新都区',
                  label: '新都区',
                },
                {
                  value: '郫都区',
                  label: '郫都区',
                },
                {
                  value: '温江区',
                  label: '温江区',
                },
                {
                  value: '双流区',
                  label: '双流区',
                },
                {
                  value: '青白江区',
                  label: '青白江区',
                },
                {
                  value: '天府新区',
                  label: '天府新区',
                },

              ]
            }
          ]
        },
      ],
      addHouseForm:{
        type:[],
        add:[],
        province:'',
        city:'',
        county:'',
        address:'',
        money:'',
        area:'',
        describe:'',
        houseType:'',
        floor:'',
        buildTime: '',
        rentType:'',
        peopleNum: '',
        state:'',
        shiType:'',
        tingType:'',
      },
      addHouseRules:{
        add:[
          { required: true, message: '请选择地区', trigger: 'blur' }
        ],
        address:[
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        money:[
          { required: true, message: '请输入租金', trigger: 'blur' }
        ],
        area:[
          { required: true, message: '请输入面积', trigger: 'blur' }
        ],
        floor:[
          { required: true, message: '请输入楼层', trigger: 'blur' }
        ],
        buildTime:[
          { required: true, message: '请输入修建时间', trigger: 'blur' }
        ],
        rentType:[
          { required: true, message: '请选择出租类型', trigger: 'blur' }
        ],
        peopleNum:[
          { required: true, message: '请输入合租人数', trigger: 'blur' }
        ],
        shiType: [
          { required: true, message: '请选择房源户型', trigger: 'blur' }
        ],
        tingType: [
          { required: true, message: '请选择房源户型', trigger: 'blur' }
        ]
      },
      paneShow:{
        updateHouse : false,
        addHouse: false
      },
      housePage:{
        pageSize:10,
        pageNo:1,
        count:10
      },
      tableTabsValue:'houseList',
      tabList:[

      ],
      lookHouseResource:false,
      provinceList:[
        {
          id:'2',
          name:'四川省'
        }
      ],
      cityList:[
        {
          id:'2',
          name:'成都市'
        }
      ],
      countyList:[
        {
          id:'1',
          name:'武侯区',

        },
        {
          id: '2',
          name: '高新区',
        },
        {
          id: '3',
          name: '锦江区',
        },
        {
          id: '4',
          name: '金牛区',
        },
        {
          id: '5',
          name: '成华区',
        },
        {
          id: '6',
          name: '龙泉驿区',
        },
        {
          id: '7',
          name: '新都区',
        },
        {
          id: '8',
          name: '郫都区',
        },
        {
          id: '9',
          name: '温江区',
        },
        {
          id: '10',
          name: '双流区',
        },
        {
          id: '11',
          name: '青白江区',
        },
        {
          id: '12',
          name: '天府新区',
        },

      ],
      otherCondition:false,
      houseList:[

      ],
      changingHouse:{
        id:'1',
        province:'四川',
        city:'成都',
        county:'龙泉驿',
        address:'十陵镇XXXX',
        money:"2000",
        area:'80',
        describe:'租户稳定,作息正常',
        houseType:'三室一厅',
        houseTypeStr:'',
        floor:'15',
        buildTime:'2016',
        rentType:'整租',
        peopleNum:'1',
        picList:[

        ],
        tagList:[
          {
            id:'1',
            name:'整租'
          },
          {
            id:'2',
            name:'近地铁'
          },
          {
            id:'3',
            name:'朝南'
          },
        ]
      },
      rentType:[
        {
          rentType:0,
          rentTypeStr:'整租'
        },
        {
          rentType:1,
          rentTypeStr: '合租'
        }
      ],
      houseType:[

      ],
      tagList:[

      ],
      findHouse:{
        rentType:'',
        houseType:'',
        minArea:'',
        maxArea:'',
        minRentMoney:'',
        maxRentMoney:'',
        tagList:[],
        province:'',
        city:'',
        county:'',
        condition:''
      },
      user:{

      }
    }
  },
  methods:{
    //初始化地图
    initMap(){
      // console.log(this.mapInited)
      if(this.mapInited){
        // console.log(true)
        return
      }
      //定义地图中心点坐标
      var center = new TMap.LatLng(this.map.latitude, this.map.longitude)
      //定义map变量，调用 TMap.Map() 构造函数创建地图
      var that = this;
      this.$nextTick(()=>{
        var map = new TMap.Map(document.getElementById('myMap'), {
          center: center,//设置地图中心点坐标
          zoom: 17.2,   //设置地图缩放级别
          pitch: 43.5,  //设置俯仰角
          rotation: 45,    //设置地图旋转角度
          //设置地图为2D
          viewMode:'2D',
        });

        //初始化marker图层
        var markerLayer = new TMap.MultiMarker({
          id: 'marker-layer',
          map: map
        });
        markerLayer.add({
          position:center
        })
        let lng;
        let lat;
        map.on('click', (event)=>  {
          // 获取点击后的地图坐标
          lng = String(event.latLng.getLng());
          lat = String(event.latLng.getLat());
          //改变标记点的坐标
          // console.log(lat,lng)
          markerLayer.setMap(null);
          markerLayer = new TMap.MultiMarker({
            id: 'marker-layer',
            map: map
          });
          var sign = new TMap.LatLng(lat, lng)
          markerLayer.add({
            position:sign
          })
          //设置房源的经纬度
          // console.log("纬度"+lat)
          // console.log("经度"+lng)
          this.map.latitude = lat;
          this.map.longitude = lng;
        })
        this.mapInited = true;
      })

    },
    verifyFail(){
      //审核不通过
      this.$prompt('请输入不通过理由','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputErrorMessage:'请输入原因！',
        inputValidator:(value=>{
          if(value){
            return true;
          }else{
            return false;
          }
        })
      }).then(value=>{
        //向后端发送请求，修改这条信息的状态
        let params = {
          id:this.changingHouse.id,
          state:3,
          remake:value.value,
        }
        this.$network.saveHouse(params).then(res=>{
          //退出标签页
          if(res.data.code=='200'){
            this.$message({
              message:'操作成功',
              type:'success'
            })
          }
          //向房东发送审核成功的消息
          let params = {
            receiverType:'0',
            receiverId:this.changingHouse.createBy.id,
            title:'房源审核未通过',
            text:baseMessage.examineFail(this.changingHouse.id),
            state:0
          }
          //向后端发送请求，增加消息
          this.$network.addMessage(params).then(res=>{

          }).catch(err=>{
            console.log(err)
          })
          //关闭标签页
          this.tabList=[];
          this.tableTabsValue='houseList';
          //重新查询房源数据
          params = {
            pageNo:this.housePage.pageNo,
            pageSize:this.housePage.pageSize
          }
          this.findHousePage(params)
        }).catch(err=>{
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    verifySuccess(){
      this.$confirm('确定通过这个房源记录吗？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res=>{
        //审核通过，将房源的状态改为正在出租
        let params ={
          id:this.changingHouse.id,
          state:1
        }
        //修改房源数据
        this.$network.saveHouse(params).then(res=>{
          if(res.data.code=='200'){
            this.$message({
              message:'成功',
              type:'success'
            })
            //向房东发送审核成功的消息
            let params = {
              receiverType:'0',
              receiverId:this.changingHouse.createBy.id,
              title:'房源审核通过',
              text:baseMessage.examineSuccess(this.changingHouse.id),
              state:0
            }
            //向后端发送请求，增加消息
            this.$network.addMessage(params).then(res=>{

            }).catch(err=>{
              console.log(err)
            })
          }
          //关闭标签页
          this.tabList=[];
          this.tableTabsValue='houseList';
          //重新查询房源数据
          params = {
            pageNo:this.housePage.pageNo,
            pageSize:this.housePage.pageSize
          }
          this.findHousePage(params)
        })
      })
    },
    changeOtherCondition(){
      this.otherCondition = !this.otherCondition;
    },
    handleTabsEdit(targetName, action){
      if(action==='remove'){
        this.tabList=[];
        this.tableTabsValue='houseList'
        this.mapInited = !this.mapInited;
      }
    },
    changeHouseInfo(item){
      //向后台发送请求，查询该房源的所有信息
      this.tabList = [{
        title: '查看房源',
        name: 'lookHouse'
      }];
      this.tableTabsValue='lookHouse';
      this.paneShow.addHouse = false;
      this.paneShow.updateHouse = true;
      this.changingHouse = item;
    },
    sizeChange(val){
      this.housePage.pageSize = val;
      this.findHouseByCondition();
    },
    currentChange(val){
      this.housePage.pageNo = val;
      this.findHouseByCondition();
    },
    prevClick(val){
      // console.log('prev')
      // this.housePage.pageNo = val;
      // this.findHouseByCondition();
    },
    nextClick(val){
      // console.log(val)
      // this.housePage.pageNo = val;
      // this.findHouseByCondition();
    },
    addHouseResource(){
      this.houseBaseInfoShow = true;
      this.addHouseStep = 1;
      this.tabList = [{
        title: '增加房源',
        name: 'addHouse'
      }];
      this.tableTabsValue='addHouse';
      this.paneShow.updateHouse = false;
      this.paneShow.addHouse = true;
    },
    roommates(val){
      if(this.addHouseForm.rentType=='整租'){
        this.peopleView = false;
      }else{
        this.peopleView = true;
      }
    },
    add(){
      this.$refs.addHouseForm[0].validate((valid) => {
        if (valid) {
          let cTagList = JSON.parse(JSON.stringify(this.chooseTagList).replace(/id/g,"tagId"));
          //整合向后端发送的参数
          let params = {
            province:this.addHouseForm.add[0],
            city:this.addHouseForm.add[1],
            county:this.addHouseForm.add[2],
            address:this.addHouseForm.address,
            money:this.addHouseForm.money,
            area:this.addHouseForm.area,
            describe:this.addHouseForm.describe,
            // houseType:this.addHouseForm.shiType+"室"+this.addHouseForm.tingType+"厅",
            //房源位置
            latitude:this.map.latitude,
            longitude:this.map.longitude,
            houseType:this.addHouseForm.houseType,
            floor:this.addHouseForm.floor,
            buildTime: this.addHouseForm.buildTime,
            rentType:this.addHouseForm.rentType=='整租'?0:1,
            peopleNum: this.addHouseForm.rentType=='整租'?1:this.addHouseForm.peopleNum,
            state:0,
            picList: this.uploadPhotoList,
            tagList:cTagList
          }
          //调用后端接口
          this.$network.addHouseResource(JSON.stringify(params)).then(res=>{
            if(res.data.code=='200'){
              this.$message.success("新增成功")
              this.tabList=[];
              this.tableTabsValue='houseList';
              this.mapInited = !this.mapInited;
              //重新查询一遍后端接口，返回房源
              this.housePage.pageNo = 1;
              this.housePage.pageSize = 10;
              let params = {
                pageNo:this.housePage.pageNo,
                pageSize:this.housePage.pageSize,
              }
              this.findHousePage(params)
            }else{
              this.$message.error("新增出现错误")
              this.tabList=[];
              this.tableTabsValue='houseList';
            }
          }).catch(err =>{
            console.log(err)
          })
        } else {
          return false;
        }
      });
    },
    cancel(){
      this.tabList=[];
      this.tableTabsValue='houseList';
      this.mapInited = !this.mapInited;
    },
    handleRemove(file) {
      this.uploadPhotoList.forEach((value, index) => {
        if(value.name==file.name){
          this.uploadPhotoList.splice(index,1)
        }
      })
    },
    addTag(){
      this.allTagList.forEach(t=>{
        if((t.id)==this.chooseTag){
          if(!this.chooseTagList.includes(t)){
            this.chooseTagList.push(t)
          }
          return;
        }
      })

    },
    handlePreview(file){
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    findHouseByCondition(){
        //处理tagList参数
        let chooseTagList = [];
        for (let i = 0;i<this.findHouse.tagList.length;i++){
          for (let j = 0;j<this.allTagList.length;j++){
            if(this.allTagList[j].id===this.findHouse.tagList[i]){
              chooseTagList.push(this.allTagList[j])
            }
          }
        }
        //将查询条件封装为对象参数
        let params = {
          pageNo:this.housePage.pageNo,
          pageSize:this.housePage.pageSize,
          rentType:this.findHouse.rentType,
          houseType:this.findHouse.houseType,
          minArea:this.findHouse.minArea,
          maxArea:this.findHouse.maxArea,
          minMoney:this.findHouse.minRentMoney,
          maxMoney:this.findHouse.maxRentMoney,
          tagList:chooseTagList,
          province:this.findHouse.province,
          city:this.findHouse.city,
          county:this.findHouse.county,
          condition:this.findHouse.condition
        }
        this.findHousePage(params)
    },
    housePicUpload(response, file, fileList){
      let url = response.data;
      let name = file.name;
      let temp = {
        url:url,
        name:name
      }
      this.uploadPhotoList.push(temp)
    },
    beforeUpload(){
      if (localStorage.getItem('token')) {
        this.uploadHeaders.token = localStorage.getItem('token');
      }
    },
    closeTag(tag){
      for (let i = 0;i<this.chooseTagList.length;i++){
        if(this.chooseTagList[i].id==tag.id){
          this.chooseTagList.splice(i,1);
        }
      }
    },
    nextStep(){
      this.addHouseStep = 2;
      this.houseBaseInfoShow = false;
      //向后端发送请求，查询所有的标签
      this.$network.findAllTags().then(res=>{
        this.allTagList = res.data.data;
      })
      this.initMap()
    },
    prevStep(){
      this.addHouseStep = 1;
      this.houseBaseInfoShow = true;
    },
    findHousePage(params){
      //判断当前登录用户的角色，如果为房东，那么就查询与房东相关的房源
      let role = JSON.parse(localStorage.getItem("loginData")).role;
      // console.log(JSON.parse(localStorage.getItem("loginData")).role)
      if(role==1){
        this.findHouseByRole(params)
        return
      }else if(role==2){
        params.state=0
      }
      this.$network.findHousePageJson(params).then(res=>{
        if(res.data.code=='200'){
          this.houseList = res.data.data.list;
          this.housePage.count = res.data.data.count;
        }
      })
    },
    findHouseByRole(params){
      this.$network.findHouseByRole(params).then(res=>{
        if(res.data.code=='200'){
          this.houseList = res.data.data.list;
          this.housePage.count = res.data.data.count;
        }
      })
    },
    getLongitudeLatitude() {
      var _this = this;
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          //locationSuccess 获取成功的话
          function (position) {
            _this.map.longitude = position.coords.longitude;
            _this.map.latitude = position.coords.latitude;
            console.log(_this.getLatitude,_this.getLatitude)
          },
          //locationError  获取失败的话
          function (error) {
            var errorType = [
              "您拒绝共享位置信息",
              "获取不到位置信息",
              "获取位置信息超时",
            ];
            console.log(errorType[error.code - 1]);
          }
        );
      }
    },
    deleteHouse(id){
      //删除信息
      this.$confirm('确定删除这条房源信息吗？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res=>{
        //向后端发送请求，删除这条房源信息
        let params = {
          id:id
        }
        this.$network.deleteHouse(params).then(res=>{
          if(res.data.code=='200'){
            this.$message({
              message:'删除成功',
              type:'success'
            })
            this.findHouseByCondition();
          }
        }).catch(err=>{
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
  beforeMount() {
    //向后端发送请求，查询所有的标签
    this.$network.findAllTags().then(res=>{
      this.allTagList = res.data.data;
    })
    //向后端发送请求，通过字典查询所有的户型
    let params = {
      type:'house_type'
    }
    this.$network.findAllJson(params).then(res=>{
      this.houseType  = res.data.data
    }).catch(err=>{
      console.log(err)
    })

    params = {
      pageNo:1,
      pageSize:10
    }
    this.findHousePage(params);
    this.user = JSON.parse(localStorage.getItem("loginData"));
  },
  mounted() {
    // this.initMap()
    //此方法谷歌浏览器禁用
    // var _this = this;
    // if(navigator.geolocation) {
    //   navigator.geolocation.getCurrentPosition(
    //     //locationSuccess 获取成功的话
    //     function(position) {
    //       _this.map.longitude = position.coords.longitude;
    //       _this.map.latitude = position.coords.latitude;
    //
    //     },
    //     //locationError  获取失败的话
    //     function(error) {
    //       var errorType = ['您拒绝共享位置信息', '获取不到位置信息', '获取位置信息超时'];
    //       alert(errorType[error.code - 1]);
    //     }
    //   );
    // }
  },
  created() {
    /**
     * 获取定位
     */
    // console.log("create")
    let data = {
      key:this.key
    };
    let url = this.getLocationUrl;
    data.output = "jsonp";
    //使用jsonp访问，防止跨域
    this.$jsonp(url,data).then(res=>{
      // console.log(res)
      this.map.latitude = res.result.location.lat;
      this.map.longitude = res.result.location.lng;
    }).catch(err=>{
      console.log(err)
    })

  }
}
</script>

<style scoped>
.upload-demo{
  margin-top: 30px;
}

.addStep{
  height: 300px;
  position: absolute;
}
.houseList{
  height: 560px;
  /*height: 65vh;*/
  overflow: scroll;
  overflow-x: hidden !important;
}

h1{
  text-align: center;
}

.hoseImage{
  height: 180px;
  width: 225px;
  float: left;
}
.simple{
  font-size: 20px;
  font-family: 华文新魏;
  color: darkorange;
}

.describe{
  text-align: left;
  margin: 10px;
  font-size: 15px;
  font-family: 微软雅黑;
}

.price{
  margin: 0px;
}

.price>span{
  font-size: 30px;
  color: red;
  font-family: 新宋体;
}

.tag{
  height: 20px;
}



.el-tag{
  margin: 5px;
}

.changeHouseInfo{
  margin-top: 10px;
}

.houseArea{
  width: 60px;
}

.rentMoney{
  width: 90px;
}

.otherCondition{
  color: deepskyblue;
}

.address{
  width: 150px;
}

.changeHouse{
  width: 1200px;
  margin: 0 auto;
}

.addHouse{
  width: 500px;
  margin: 0 auto;
}

.el-input__inner {
  width: 300px;
}

.addHouseType{

  float: right;
}

.addBtn>*{
  margin: 30px 30px;
}

.addHouseInput{
  width: 300px;
  float: right;
}

.checkBtn>*{
  margin: 30px 30px;
}

#myMap{
  width: 600px;
  height: 300px;
}

.housePage{
  margin-top: 10px;
}

.funBtn{
  display: flex;
}

.houseState{
  display: flex;
  width: 50%;
}

.options>*{
  margin-left: 30px;
}
</style>
